import sqlite3 as sql
import subprocess, traceback

# import contextlib
# 
import sys, io, os
# import ctypes
# colors = ctypes.CDLL('./colors.so')
# colors.colorize_name.argtypes = (ctypes.char_p, ctypes.int, ctypes.char_p) 

# get all maps in database 
def get_map_list(database):
    output = []
    con  = sql.connect(database)
    with con:
        cursor = con.cursor()
        try:
            cursor.execute("select distinct mapid from Cts_times;")
            output = cursor.fetchall()
        except sql.Error:
            print("Shit is fucked.")
    return output

# if there is no query then it outputs the index file.
def run_cgi(query=None):
    cmd  = [("./cts")]
    proc = subprocess.Popen(cmd, env=query, stdout=subprocess.PIPE, shell=True)
    # communicate returns 'bytes' class with function 'decode'
    return proc.communicate()[0].decode('utf-8')

def run_colors(player_name):
    ret    = player_name
    result = subprocess.run(['./colors', player_name], capture_output=True, text=True)
    if result.returncode == 0:
        ret = result.stdout
    return ret

def get_speed_record(database, map_id):
    message = "{name} traveled the fastest at {speed} qu/s."
    query = str()
    result = []
    with open("queries/fastest-player-of-map.sql") as f:
        query = f.read()
    # q =  query.replace('?', map_id) 
    # print(q)
    with sql.connect(database) as con:
        cursor = con.cursor()
        try:
            cursor.execute(query, (map_id,))
            result = cursor.fetchall()
        except sql.Error:
            pass
    player_name = result[0][1]
    colored = (run_colors(player_name)).strip()
    velocity = round(result[0][0], 2)
    return message.format(name=colored, speed=velocity)
    

def main():
    template = ""
    with open("overview.html", 'r') as fin:
        template = fin.read()
        with open("output/index.html", 'w') as fout:
            fout.write(template % run_cgi())
        # use same template for fastest-players
        query = {"QUERY_STRING" : "fastest-players"}
        with open("output/fastest-players.html", 'w') as fout:
            fout.write(template % run_cgi(query))
    maps  = get_map_list("db/cts.db")
    with open("map.html", 'r') as fin:
        template = fin.read()
    # for each map generate an html file.
    for game_map in maps:
    # game_map is a tuple obj.
        map_name = game_map[0]
        query    = {"QUERY_STRING" : ("map=%s" % map_name)}
        filename = ("output/maps/%s.html" % map_name)
        sentence = get_speed_record("db/cts.db", map_name)
        with open(filename, 'w+') as fout:
            title = map_name
            fout.write(template.format(
                title=title, 
                map_name=map_name, 
                table=run_cgi(query),
                speed=sentence
                )
            )
            # fout.write(template % (title, map_name, table))
    return True

if __name__ == "__main__":
    success = False
    try:
        success = main()
    except FileNotFoundError:
        traceback.print_exc()
        print("\n\t The script probably didn't find the page templates needed to generate a page. You can copy minimal working examples from the repository at templates/.")
    if success:
        print("allmaps.py - Generated pages for all maps.")
    pass
